import oled as OLED
import socket
import subprocess
import re
from datetime import datetime
import threading
import time
import psutil  # 导入 psutil 库

DEBUG = False  # 设置为 True 以启用打印输出

def debug_print(*args, **kwargs):
    if DEBUG:
        print(*args, **kwargs)

def get_host_ip():
    ip = "无法获取IP"
    def fetch_ip():
        nonlocal ip
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 80))
            ip = s.getsockname()[0]
        except Exception as e:
            ip = f"IP获取错误: {e}"
        finally:
            s.close()
    thread = threading.Thread(target=fetch_ip)
    thread.start()
    thread.join(timeout=5)
    return ip

def get_cpu_temperature():
    try:
        # 直接从系统文件获取温度
        with open("/sys/class/thermal/thermal_zone0/temp", "r") as f:
            temp = f.read().strip()
            temp_celsius = float(temp) / 1000.0  # 转为摄氏度
            return f"CPU_temp: {temp_celsius:.1f} °C"
    except Exception as e:
        return f"获取温度失败: {e}"

def get_cpu_usage():
    return f"CPU_usage: {psutil.cpu_percent()}%"  # 获取 CPU 使用率

def get_ram_usage():
    ram = psutil.virtual_memory()
    return f"RAM_usage: {ram.percent}%"  # 获取 RAM 使用率

def update_display():
    try:
        ip = get_host_ip()
    except Exception as e:
        ip = f"IP获取错误: {e}"
    
    try:
        curr_time = datetime.now()
        today = curr_time.strftime("%Y-%m-%d")
        today = "DATE: " + today
    except Exception as e:
        today = f"日期获取错误: {e}"

    try:
        cpu_temp = get_cpu_temperature()
    except Exception as e:
        cpu_temp = f"温度获取错误: {e}"

    cpu_usage = get_cpu_usage()
    ram_usage = get_ram_usage()

    # 显示信息
    debug_print("显示IP:", ip)
    debug_print("显示日期:", today)
    debug_print("显示CPU温度:", cpu_temp)
    debug_print("显示CPU使用率:", cpu_usage)
    debug_print("显示RAM使用率:", ram_usage)
    
    # OLED.ShowString(22, 0, "One-KVM", 16, 1)
    # OLED.ShowString(0, 16, ip, 16, 1)
    # OLED.ShowString(0, 16 * 2, today, 16, 1)
    # OLED.ShowString(0, 16 * 3, cpu_temp, 16, 1)
    # OLED.ShowString(0, 16 * 4, cpu_usage, 16, 1)
    # OLED.ShowString(0, 16 * 5, ram_usage, 16, 1)
    OLED.ShowString(0, 0, ip, 16, 1)
    # OLED.ShowString(0, 16, today, 16, 1)
    OLED.ShowString(0, 16, cpu_temp, 16, 1)
    OLED.ShowString(0, 16 * 2, cpu_usage, 16, 1)
    OLED.ShowString(0, 16 * 3, ram_usage, 16, 1)
    OLED.Refresh()

def __main__():
    debug_print("初始化OLED...")
    OLED.Init()
    debug_print("清除OLED...")
    OLED.Clear()

    # 在 __main__ 中调用 update_display
    while True:
        update_display()  # 更新 OLED
        time.sleep(5)  # 每 5000 毫秒刷新一次

if __name__ == "__main__":
    try:
        __main__()
    except KeyboardInterrupt:
        print("程序被中断，正在退出...")
        OLED.Clear()
        OLED.ShowString(0, 0, "程序已退出", 16, 1)
        OLED.Refresh()
